<?php

namespace app\api\repository;

use app\common\Model\UserBalance;
use think\Collection;
use app\common\Model\PayLog;
use app\common\Model\User;
use app\common\Model\UserOpenid;
use app\common\Model\UserVoucher;
use app\common\Service;
use think\Config;

class UserRepository extends Service
{

    /**
     * 获取用户信息
     * @param $mobile
     * @return array
     */
    public function userInfo($key, $type = 'uid',$client = 'miniprogram')
    {
        if ($type == 'unionid') {
            $user = User::get(['unionid' => $key]);
        } elseif ($type == 'mobile') {
            $user = User::get(['mobile' => $key]);
        } else {
            $user = User::get($key);
        }

        if (!$user) {
            return [];
        }

        $user = User::get($user->uid)->toArray();

        $app_id = Config::get('wx_'.$client.'.app_id');
        $open = UserOpenid::get(['uid' => $user['uid'],'appid' => $app_id]);
        $user['openid'] = $open->openid ?? '';

        $vouchers = $this->userVouchers($user['uid']);
        $user['vouchers'] = $vouchers[0];

        $user['birthday'] = str_replace('0000-00-00', '', $user['birthday']);

        $user_balance = UserBalance::get(['uid' => $user['uid']]);

        $user['balance'] = '0.01';
        $user['total_balance'] = sprintf("%.2f", ($user_balance['recharge_balance'] + $user_balance['withdraw_balance']) / 100);

        unset($user['salt']);
        unset($user['token_expired']);
        unset($user['region_id']);
        unset($user['is_withdraw']);
        unset($user['withdraw_reason']);
        unset($user['withdraw_pwd']);
        unset($user['create_time']);
        unset($user['update_time']);

        return $user;
    }

    /**
     * 获取用户优惠券信息
     * @param $uid
     * @param string $type count 总数 list列表
     * @param string $status 1 有效 2已使用 3已过期 4 未到期
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function userVouchers($uid, $type = 'count', $status = 1, $current_page = 1, $per_page = 10)
    {
        $date = date('Y-m-d H:i:s');
        //查询有效优惠券数量

        $model = new UserVoucher();

        $sql = $model->where(['uid' => $uid]);

        //有效优惠券
        if ($status == 1) {
            $sql = $sql->where(['status' => 1])
                ->where('use_start_time', '<', $date)
                ->where('use_end_time', '>', $date);
        } elseif ($status == 2) {
            $sql = $sql->where(['status' => 2])
                ->where('use_start_time', '<', $date)
                ->where('use_end_time', '>', $date);
        } elseif ($status == 3) {
            //查询已失效优惠券 包括未到期已过期
            $sql = $sql->where("use_end_time < '$date' or use_start_time > '$date'");
//            $sql = $sql->where('use_end_time','<',$date);
//        }else{
//            $sql = $sql->where('use_start_time','>',$date);
        }

        if ($type == 'count') {
            $rtn = $sql->column('count(*)');
        } else {
            //组织分页信息
            $paginate = [
                'page' => $current_page,
            ];
            $rtn = $sql->paginate(intval($per_page), false, $paginate)->toArray();

            foreach ($rtn['data'] as &$item) {
                //未到期
                if ($item['use_start_time'] > $date) {
                    $item['status'] = 4;
                } elseif ($item['use_end_time'] < $date) {
                    $item['status'] = 3;
                }
            }
        }
        return $rtn;
    }

    /**
     * 用户的余额 返回的单位都为分：
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userBalance($uid)
    {
        if (empty($uid)) {
            return [
                'code' => 'fail',
                'msg' => '用户ID不能为空',
            ];
        }

        $model = model('app\common\Model\UserBalance');
        $res = $model
            ->where('uid', $uid)
            ->find();

        if ($res == null) {
            $res = UserBalance::createUserWallet($uid);
            return [
                'code' => 'success',
                'data' => $res,
            ];
        }

        return [
            'code' => 'success',
            'data' => $res->getData(),
        ];

    }

    /**
     * 用户消费记录
     */
    public function userExpenceLog($uid, $current_page = 1, $per_page = 10)
    {
        $model = model('app\common\Model\PayLog');
        $res = $model
            ->where('uid', $uid)
            ->where('status',1)
            ->order('update_time desc')
            ->paginate(intval($per_page), false, ['page' => $current_page])
            ->toArray();
        
        if ($res) {
            foreach ($res['data'] as $k => $v) {
                if (in_array($v['pay_event'],[1,4,5])) {
                    $res['data'][$k]['amount'] = '+' .  sprintf("%.2f",$v['amount']/config('convert_unit'));
                }else{
                    $res['data'][$k]['amount'] = '-' .  sprintf("%.2f",$v['amount']/config('convert_unit'));
                }

                $res['data'][$k]['pay_event'] = PayLog::$pay_event[$v['pay_event']];
                $res['data'][$k]['pay_channel'] = PayLog::$pay_channel[$v['pay_channel']];
            }
        }
        return $res;}


}